

import java.awt.AWTException;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import javax.imageio.ImageIO;

public class ScreenServer implements Runnable {
	private final int PORT = 8887;
	static BufferedImage screenCapture;
	String ip;

	public ScreenServer(String ipA) {
		this.ip = ipA;
	}

	public void run() {
		try {
			Thread.sleep(10L);
			Socket s = new Socket();
			s.connect(new InetSocketAddress(this.ip, 8887));

			Rectangle screen = new Rectangle(Toolkit.getDefaultToolkit()
					.getScreenSize());
			screenCapture = new Robot().createScreenCapture(screen);
			Image cursor = ImageIO.read(new File("pointer.gif"));
			int x = MouseInfo.getPointerInfo().getLocation().x;
			int y = MouseInfo.getPointerInfo().getLocation().y;
			Graphics2D graphics2D = screenCapture.createGraphics();
			graphics2D.drawImage(cursor, x, y, 16, 16, null);

			new Thread(new FileServerClient(s)).start();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AWTException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	static class FileServerClient implements Runnable {
		private Socket socket;

		FileServerClient(Socket s) {
			this.socket = s;
		}

		public void run() {
			try {
				BufferedOutputStream out = new BufferedOutputStream(
						this.socket.getOutputStream());
				ImageIO.write(ScreenServer.screenCapture, "GIF", out);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
				try {
					this.socket.close();
				} catch (IOException ex) {
					e.printStackTrace();
				}
			} finally {
				try {
					this.socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}